package org.team4u.demo.fsh.web;

import com.asiainfo.common.util.Callback2;
import com.asiainfo.common.util.ServiceProvider;
import com.asiainfo.dao.core.SimpleDao;
import org.team4u.fhs.server.HttpServer;
import org.team4u.fhs.server.HttpServerRequest;
import org.team4u.fhs.server.HttpServerResponse;
import org.team4u.fhs.server.impl.netty.NettyHttpServer;
import org.team4u.fhs.server.impl.netty.NettyHttpServerConfig;
import org.team4u.fhs.web.DefaultHttpRouter;
import org.team4u.fhs.web.HttpRouter;
import org.team4u.fhs.web.RoutingContext;
import org.team4u.fhs.web.ext.view.BeetlViewResolver;
import org.team4u.fhs.web.ext.view.FastJsonViewResolver;
import org.team4u.fhs.web.handler.method.RequestMappingHandlerMapping;
import org.team4u.fhs.web.handler.resource.StaticResourceHandlerMapping;

import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;

/**
 * @author Jay Wu
 */
public class WebServer implements Closeable {

    private HttpServer httpServer;

    public WebServer(DataSource dataSource) {
        ServiceProvider.getInstance().register(new SimpleDao(dataSource));

        final HttpRouter router = new DefaultHttpRouter()
                .addLastHandlerMapping(new RequestMappingHandlerMapping()
                        .addController(new TestController())
                )
                .addLastHandlerMapping(new StaticResourceHandlerMapping("webapp/static", "static"))
                .addLastViewResolver(new BeetlViewResolver())
                .addLastViewResolver(new FastJsonViewResolver());

        httpServer = new NettyHttpServer(new NettyHttpServerConfig())
                .onRequest(new Callback2<HttpServerRequest, HttpServerResponse>() {
                    @Override
                    public void invoke(HttpServerRequest request, HttpServerResponse response) {
                        router.doRoute(new RoutingContext()
                                .setRequest(request)
                                .setResponse(response));
                    }
                });
    }

    public void start(int port) {
        httpServer.listen(port);
    }

    @Override
    public void close() throws IOException {
        httpServer.close();
    }

    public static void main(String[] args) {
        new WebServer(TestUtil.createAndInitDao().getDataSource())
                .start(7000);
    }
}